package com.ruoyi.pcj.docking.zego.core;

import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.util.Base64;

/**
 * @ClassName: ZegoUtils
 * @Author : mashuai
 * @Description: TODO
 */
public class ZeGoGetToken {

    /**
     * 获取token
     *
     * @param appId
     * @param serverSecret
     * @param userId
     * @return
     */
    public static String getToken(Long appId, String serverSecret, String userId) {

        int effectiveTimeInSeconds = 60 * 60 * 24;   // 有效时间，单位：秒
        // // 基础鉴权 token，payload字段可传空
        String payload = "{\"payload\":\"payload\"}";  // 填入自定义的payload值，如示例payload字段。 非必输，不传则赋值null。
        TokenServerAssistant.VERBOSE = true;    // 调试时，置为 true, 可在控制台输出更多信息；正式运行时，最好置为 false
        TokenServerAssistant.TokenInfo token = TokenServerAssistant.generateToken04(appId, userId, serverSecret, effectiveTimeInSeconds, payload);
        System.err.println(token);
        if (token.error == null || token.error.code == TokenServerAssistant.ErrorCode.SUCCESS) {
            System.out.println("\r\ndecrypt the token ...");
            decryptToken(token.data, serverSecret);
            System.err.println(token);
        }
        return token.data;
    }


    static private void decryptToken(String token, String secretKey) {
        String noVersionToken = token.substring(2);
        byte[] tokenBytes = Base64.getDecoder().decode(noVersionToken.getBytes());
        ByteBuffer buffer = ByteBuffer.wrap(tokenBytes);
        buffer.order(ByteOrder.BIG_ENDIAN);
        long expiredTime = buffer.getLong();
        System.out.println("expiredTime: " + expiredTime);
        int IVLength = buffer.getShort();
        byte[] ivBytes = new byte[IVLength];
        buffer.get(ivBytes);
        int contentLength = buffer.getShort();
        byte[] contentBytes = new byte[contentLength];
        buffer.get(contentBytes);
        try {
            SecretKeySpec key = new SecretKeySpec(secretKey.getBytes(), "AES");
            IvParameterSpec iv = new IvParameterSpec(ivBytes);
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            cipher.init(Cipher.DECRYPT_MODE, key, iv);
            byte[] rawBytes = cipher.doFinal(contentBytes);
            JSONParser parser = new JSONParser();
            JSONObject json = (JSONObject) parser.parse(new String(rawBytes));
            System.out.println(json);
        } catch (Exception e) {
            System.out.println("decrypt failed: " + e);
        }
    }
}
